# -*- coding: utf8 -*-
#引入数据库的对应download1方法 面对普通网页情况
import urllib2
import urllib
import re
import os
import time
import sqlite3
import zlib
def download(url,category):
    content=urllib2.urlopen(url).read()
    name_pat=re.compile('<meta name="author" content="(.*?)">')
    time_pat=re.compile('id="PAGETIME" value="(.*?)">')
    namestr=re.findall(name_pat,content)[0]
    timestr=re.findall(time_pat,content)[0]
    t=(category,namestr.decode('utf-8'),timestr.decode('utf-8'),buffer(zlib.compress(content)))
    try:
        conn = sqlite3.connect("E:/test.db")
    except sqlite3.Error,e:
        print('连接sqlite3数据库失败')
        return(0)
    conn.isolation_level = None
    '''
    #删除模块 方便清空
    try:
        conn.execute('DROP TABLE IF EXISTS t3;')
    except sqlite3.Error,e:
        print('删除数据库表失败')
        return
    '''
    conn.execute("create table if not exists t3(id integer primary key autoincrement,title TEXT, name TEXT UNIQUE, time TEXT,info blob)")
    try:
        conn.execute('insert into t3(title,name,time,info) values (?,?,?,?)',t)
    except:
        return(0)
    print(category)
    print(namestr.decode('utf-8'))
    cur = conn.cursor()
    '''
    # 用游标来查询就可以获取到结果
    #cur.execute(u"select * from t3 where name like '%'")
    #for row in cur.fetchall():
        #print row[1]
    cur.execute("select * from t3")
    for row in cur.fetchall():
        print row[1],row[2],row[3]
    '''
    cur.close()
    conn.close()
    time.sleep(0.001)
    '''
    filename='N'+re.findall(name_pat,content)[0]+'T'+re.findall(time_pat,content)[0]+'.xml'
    filename=filename.replace(":","-")
    filename=filename.replace('/','~')
    filename="F:\Python27\Zgr03"+os.sep+category+os.sep+filename.decode('utf-8')
    #print(temple)
    #print(temple[0])
    time.sleep(0.01)
    '''
    return(1)
#url=('http://www.baike.com/wiki/%E8%B4%A8%E5%AD%90-K%2FD%E7%BB%84%E7%BA%A7%E8%BF%90%E8%BD%BD%E7%81%AB%E7%AE%AD')
#category='\xe9\x99\xa2\xe5\xa3\xab'
#category=category.decode('utf-8')

#download(url,category)
